package crafex.engine.system;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

/**yes i know how to spell system, i spelled it this way to avoid confution of the java System*/
public class Systum extends Thread{
	
	/**if the game is running*/
	private static boolean running;
	/**if the game is active*/
	private static boolean playing;
	/**the max frames allowed per second*/
	public static int FPS = 10;
	public static int ONE_SECOND_MILLI = 1000;
	/**the view of the android*/
	private SurfaceHolder view;
	/**the game systems*/
	private Crafex crafex;
	
	public Systum(Crafex crafex, int fps){
		this.crafex = crafex;
		view = crafex.getHolder();
	}
	
	/**sets running to true*/
	public void startRunning(){
		running = true;
	}
	
	/**sets running to false*/
	public void kill(){
		running = false;
	}
	
	/**
	 * sets if the game is active or not
	 * @param isPlaying
	 */
	public static void setPlaying(boolean isPlaying){
		playing = isPlaying;
	}
	
	/**
	 * gets if the game is active
	 * @return playing
	 */
	public boolean isPlaying(){
		return playing;
	}
	
	/**
	 * the method containing the game loop
	 */
	public void run(){
		
		long frameLength = ONE_SECOND_MILLI / FPS;
		long startingTime;
		long sleepTime;
		
		while(running){
			startingTime = System.currentTimeMillis();
			Canvas canvas = null;
			
			try {
				canvas = view.lockCanvas();
				if(canvas != null){
					crafex.update();
					crafex.draw(canvas);//dev IS here
				}
			} finally {
				if (canvas != null) {
					view.unlockCanvasAndPost(canvas);
				}
			}
			
			
			sleepTime = frameLength - (System.currentTimeMillis() - startingTime);
			try {
				if (sleepTime > 0)
					sleep(sleepTime);
				else
					sleep(15);
             	} catch (Exception e) {}
		}
	}
}